#coding=utf-8
import psutil
from os import error, system,path
import configparser
config_file = str('''
#内网配置
[Intranet]
IP=172.31.0.127
GATEWAY=172.31.0.254
NETMASK=255.255.255.0
DNS1=172.31.0.254
DNS2=119.29.29.29



#外网配置
[Extranet]
IP=10.0.9.123
GATEWAY=10.0.9.254
NETMASK=255.255.255.0
DNS1=119.29.29.29
DNS2=114.114.114.114

#自定义配置1
[customize1]
IP=10.0.9.123
GATEWAY=10.0.9.254
NETMASK=255.255.255.0
DNS1=119.29.29.29
DNS2=114.114.114.114

#自定义配置2
[customize2]
IP=10.0.9.123
GATEWAY=10.0.9.254
NETMASK=255.255.255.0
DNS1=119.29.29.29
DNS2=114.114.114.114
''')

def get_ipaddr(ifname):
    """
    传入一个网卡名，然后就可以获取到这个网卡的IP地址
    """
    dic = psutil.net_if_addrs()
    ipv4_list = []
    for adapter in dic:
        if str(adapter) == str(ifname):
            snicList = dic[adapter]
            for snic in snicList:
                if snic.family.name == 'AF_INET':
                    ipv4 = snic.address
                    if ipv4 != '127.0.0.1':
                        ipv4_list.append(ipv4)
                        if len(ipv4_list)>=1:
                            return ipv4_list[0]
                        else:
                            return 'None'

#开始配置
def config(card, ip, netmask, gateway, dns1, dns2):
    dhcp_cmd = "netsh interface ipv4 set address name=\"" + card  + "\" source=dhcp"
    ip_cmd ="netsh interface ip set address name=\"" + card + "\" source=static address=" + ip + " mask=" + netmask + " gateway=" + gateway
    dns_cmd = "netsh interface ipv4 set dnsservers name=\"" + card + "\" source=static address=" + dns1 + " register=primary validate=no"
    dns2_cmd="netsh interface ipv4 add dnsservers  name=\"" + card + "\" " + dns2 +  " index=2 validate=no"
    try:
        print("正在清除配置-->[ %s ]" %dhcp_cmd)
        system(dhcp_cmd)
        print("正在设置IP--->[ %s ]" %ip_cmd)
        system(ip_cmd)
        print("正在设置DNS1-->[ %s ]" %dns_cmd)
        system(dns_cmd)
        print("正在设置DNS2-->[ %s ]" %dns2_cmd)
    except error:
        print("请检查本机是否存在此IP[ %s ]" %ip)
    d = input('按任意键终止程序')

#获取配置文件内容
def get_config(file,mode,card_name,ip_list):
    """
    file #选择一个配置文件
    mode  #选择一个section(部分)
    card_name #网卡名
    """
    if path.isfile(file):
        net_config = configparser.ConfigParser()
        net_config.read(file,encoding='utf-8')
        # Intranet = net_config.items(mode)
        IP = net_config.get(mode,"IP")
        GATEWAY = net_config.get(mode,"GATEWAY")
        NETMASK = net_config.get(mode,"NETMASK")
        DNS1 = net_config.get(mode,"DNS1")
        DNS2 = net_config.get(mode,"DNS2")
        
        for i in ip_list:
            if i == IP:
                exit("本机已存在相同的IP--->[ %s ]" %IP)
        config(card=card_name, ip=IP, netmask=NETMASK, gateway=GATEWAY, dns1=DNS1, dns2=DNS2)
    else:
        print("文件[ %s ]不存在,已新建该配置文件，请按需修改后再执行" %file)
        rw_file = open(file,'w')
        rw_file.write(config_file)
        rw_file.close()
        print(config_file)
        print('请根据需求修改以上内容--->[ %s ]' %file)
        d = input('按任意键终止程序')
        
##获取本机网卡列表
def get_netcard():
    net_mode= ''
    netcard_info = []
    ip_list = []
    info = psutil.net_if_addrs()
    for k,v in info.items():
        for item in v:
            if item[0] == 2 and not item[1]=='127.0.0.1':
                netcard_info.append((k))
                ip_list.append(item[1])
    i=0
    net_lists = []
    net_list = []
    for k in netcard_info:
        i = i + 1
        net_list.append("[ " + str(i) + " ]" + k)
        net_lists.append(k)
    print('一共有[ %s ]个网卡' %i)
    for s in net_list:
        print(s)
      
    #设置第一个网卡为默认网卡(0是第一，1是第二)
    default_card = net_lists[0]
    
    net_name = ''
    net_card = input('请选择一个网卡进行操作,默认---> ([1] %s )\n' %default_card)
    for use in range(1,i):
        if str(net_card) == str(use):
            i = int(use) - 1
            net_name = net_lists[i]
    if net_name:
        print('已选择[ %s ]' %net_name)
    else:
        net_name = default_card
        print('设置默认网卡-->[ %s ]' %net_name)
    select_net = input('''请选择需要设置的模式/IP
[1]设置内网---->[ Intranet ]
[2]设置外网---->[ Extranet ]
[3]使用自定义1->[ customize1 ]
[4]使用自定义2->[ customize2 ]
[d]设置---->[ DHCP ](默认)
[q]退出(quit)\n''')
    if str(select_net) == '1':
        net_mode = "Intranet"
    elif str(select_net) == '2':
        net_mode = "Extranet"
    elif str(select_net) == '3':
        net_mode = "customize1"
    elif str(select_net) == '4':
        net_mode = "customize2"
    else:
        net_mode = 'dhcp'
        dhcp_cmd = "netsh interface ipv4 set address name=\"" + net_name  + "\" source=dhcp"
        system(dhcp_cmd)
        d = input('已启用[ DHCP ]模式,按任意键终止程序...')
        exit('By:  坐公交也用券@(今日头条,CSDN,博客园)')
    files = input('请输入配置文件，默认[ ./connect.conf ]\n')
    if  files:
        print('已输入[ %s ]' %files)
    else:
        files='./connect.conf'
        print('未输入,已使用默认值[ %s ]' %files)

    get_config(file=files,card_name=net_name, mode=net_mode, ip_list=ip_list)
get_netcard()
exit('By:  坐公交也用券@(今日头条,CSDN,博客园)')